package com.longqin.wechat.service.impl;

import java.util.Collections;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import com.longqin.wechat.service.RedisService;
import com.longqin.wechat.util.RedisUtil;

/**redis实现类
 *
 */
@Service
public class RedisServiceImpl implements RedisService{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	
	//加锁lua脚本
	private String lock="if redis.call(\"setnx\",KEYS[1],ARGV[1]) == 1 "
						+ " then return redis.call(\"expire\",KEYS[1],ARGV[2])"
						+ " else return 0 end";

	//解锁lua脚本
	private String unLock="if redis.call(\"get\",KEYS[1]) == ARGV[1] "
							+ " then return redis.call(\"del\",KEYS[1])"
							+ " else return 0 "
						+ " end";
	
	@Resource
	private RedisUtil redisUtil;
	
	@Resource(name="lockRedisTemplate")
	private RedisTemplate<String, Object> redisTemplate;
	
	@Override
	public boolean lock(String requestId, String key, int expiresTime) {
		try {
			while(true){
				DefaultRedisScript<Long>  defaultRedisScript=new DefaultRedisScript<Long>(lock,Long.class);
				Long result=redisTemplate.execute(defaultRedisScript,Collections.singletonList(key),requestId,String.valueOf(expiresTime));
				if(null!=result && result==1){
					return true;	
				} 
				Thread.sleep(40);
			}
		} catch (InterruptedException e) {
			logger.info("获取分布式锁失败");
			return false;
		}
	}

	@Override
	public boolean releaseLock(String requestId, String key) {
		DefaultRedisScript<Long>  defaultRedisScript=new DefaultRedisScript<Long>(unLock,Long.class);
		long result=redisTemplate.execute(defaultRedisScript,Collections.singletonList(key),requestId);
		return result==1;
	}

}
